package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.common.Constants;
import com.mg.dto.PurchaseRecordDto;
import com.mg.dto.SimpleResult;
import com.mg.mapper.ContractMapper;
import com.mg.mapper.PowerAccountMapper;
import com.mg.mapper.PurchaseRecordMapper;
import com.mg.mapper.UserMapper;
import com.mg.model.Contract;
import com.mg.model.PowerAccount;
import com.mg.model.PurchaseRecord;
import com.mg.model.User;
import com.mg.service.PurchaseRecordService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class PurchaseRecordServiceImpl implements PurchaseRecordService {
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;
    @Autowired
    private PowerAccountMapper powerAccountMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ContractMapper contractMapper;

    private Logger logger = LogManager.getLogger(PurchaseRecordServiceImpl.class.getName());

    @Override
    public PageInfo<PurchaseRecordDto> selectPageInfo(PurchaseRecordDto purchaseRecordDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        if (purchaseRecordDto.getState() != null && Constants.ALL_STRING.equals(purchaseRecordDto.getState())) {
            purchaseRecordDto.setState(null);
        }
        List<PurchaseRecordDto> resultList = purchaseRecordMapper.selectPageInfo(purchaseRecordDto);
        PageInfo<PurchaseRecordDto> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public SimpleResult insertPurchaseRecord(PurchaseRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            purchaseRecordMapper.insert(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增合约收购信息失败 系统未知异常");
            logger.error("新增合约收购信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updatePurchaseRecord(PurchaseRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            PurchaseRecord record1 = new PurchaseRecord();
            record1.setId(record.getId());
            record1 = purchaseRecordMapper.selectOne(record1);
            if (record1 == null) {
                result.setSuccess(false);
                result.setMsg("该合约收购信息不存在，请刷新重试！");
            } else {
                if (Constants.PURCHASE_SUCCESS.equals(record1.getState())) {
                    result.setSuccess(false);
                    result.setMsg("该记录已经审核过，不能重复审核！");
                } else {
                    if (!record1.getState().equals(record.getState()) && Constants.PURCHASE_SUCCESS.equals(record.getState())) {
                        PowerAccount powerAccount = new PowerAccount();
                        powerAccount.setUserId(record.getUserId());
                        powerAccount.setContractId(record.getContractId());
                        powerAccount = powerAccountMapper.selectOne(powerAccount);
                        if (powerAccount == null) {
                            powerAccount = new PowerAccount();
                            powerAccount.setContractId(record.getContractId());
                            powerAccount.setUserId(record.getUserId());
                            powerAccount.setComputingPower(record.getComputingPower());
                            powerAccount.setComputingPowerNum(record.getNumber());
                            powerAccount.setFrozenComputingPower(new BigDecimal(0));
                            powerAccount.setFrozenComputingPowerNum(new BigDecimal(0));
                            powerAccount.setCreateTime(new Date());
                            powerAccountMapper.insertSelective(powerAccount);
                        } else {
                            BigDecimal power = powerAccount.getComputingPower().add(record.getComputingPower());
                            BigDecimal computingPowerNum = powerAccount.getComputingPowerNum().add(record.getNumber());
                            powerAccount.setComputingPower(power);
                            powerAccount.setUserId(record.getUserId());
                            powerAccount.setFrozenComputingPower(null);
                            powerAccount.setComputingPowerNum(computingPowerNum);
                            powerAccount.setContractId(record.getContractId());
                            powerAccount.setUpdateTime(new Date());
                            powerAccountMapper.updateByPrimaryKeySelective(powerAccount);
                        }
                        User user = new User();
                        user.setId(record.getUserId());
                        user = userMapper.selectOne(user);
                        BigDecimal balance = user.getBalance();
                        BigDecimal frozeMoney = user.getFrozeMoney();
                        balance = balance.subtract(record.getMoney());
                        frozeMoney = frozeMoney.subtract(record.getMoney());
                        user = new User();
                        user.setId(record.getUserId());
                        user.setFrozeMoney(frozeMoney);
                        user.setBalance(balance);
                        userMapper.updateByPrimaryKeySelective(user);
                    }
                    if (!record1.getState().equals(record.getState()) && Constants.PURCHASE_FAIL.equals(record.getState())) {
                        Contract contract = new Contract();
                        contract.setId(record.getContractId());
                        contract = contractMapper.selectOne(contract);
                        BigDecimal stock = contract.getStock().add(record.getNumber());
                        contract = new Contract();
                        contract.setStock(stock);
                        contract.setId(record.getContractId());
                        contractMapper.updateByPrimaryKeySelective(contract);
                        User user = new User();
                        user.setId(record.getUserId());
                        user = userMapper.selectOne(user);
                        BigDecimal frozeMoney = user.getFrozeMoney();
                        frozeMoney = frozeMoney.subtract(record.getMoney());
                        user = new User();
                        user.setId(record.getUserId());
                        user.setFrozeMoney(frozeMoney);
                        userMapper.updateByPrimaryKeySelective(user);
                    }
                    record.setUpdateTime(new Date());
                    purchaseRecordMapper.updateByPrimaryKeySelective(record);
                }

            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新合约收购信息失败 系统未知异常");
            logger.error("更新合约收购信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deletePurchaseRecord(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {

                purchaseRecordMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除合约收购信息失败 系统未知异常");
            logger.error("删除合约收购信息失败 系统未知异常", e);
        }
        return result;
    }
}
